package com.dungpt.truyenhay;

import android.app.ActionBar;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.util.Log;
import android.view.Window;
import android.widget.ListView;
import android.widget.Toast;

import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.VolleyLog;
import com.android.volley.toolbox.JsonObjectRequest;
import com.dungpt.truyenhay.adapter.CustomListStoryAdapter;
import com.dungpt.truyenhay.app.AppController;
import com.dungpt.truyenhay.model.Story;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by TienDung on 12/15/2014.
 */
public class ListBookActivity extends Activity {

    // Log tag
    private static final String TAG = ListBookActivity.class.getSimpleName();
    int cateID;

    // Stories json url
    private static final String url = "http://webtruyen.com/api2/all?page=1&perpage=2000&cate=";
    private ProgressDialog pDialog;
    private List<Story> storyList = new ArrayList<Story>();
    private ListView listView;
    private CustomListStoryAdapter adapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        getWindow().requestFeature(Window.FEATURE_ACTION_BAR_OVERLAY);
        setContentView(R.layout.activity_list_story);

        int cateID = getIntent().getExtras().getInt("cateID");
        //Toast.makeText(this, "Đọc online.. " + cateID, Toast.LENGTH_SHORT).show();

        if (!isOnline()) {
            Toast.makeText(getBaseContext(), "Không có kết nối Internet!", Toast.LENGTH_SHORT).show();
            return;
        }

        listView = (ListView) findViewById(R.id.listStory);
        adapter = new CustomListStoryAdapter(this, storyList);
        listView.setAdapter(adapter);

        pDialog = new ProgressDialog(this);
        pDialog.setMessage("Đang tải danh sách truyện...\nVui lòng đợi trong giây lát!");
        pDialog.show();

        //getActionBar().setBackgroundDrawable(new ColorDrawable(Color.parseColor("#1b1b1b")));

        String url1 = url + String.valueOf(cateID);
        JsonObjectRequest storyReq = new JsonObjectRequest(Request.Method.GET, url1, null, new Response.Listener<JSONObject>() {
            @Override
            public void onResponse(JSONObject jsonObject) {
                Log.d(TAG, jsonObject.toString());
                hidePDialog();

                JSONArray stories;
                try {
                    stories = jsonObject.getJSONArray("story");

                    for (int i = 0; i < stories.length(); i++) {
                        JSONObject obj = (JSONObject) stories.get(i);

                        Story story = new Story();
                        story.setStoryID(obj.getString("id"));
                        story.setName(obj.getString("name"));
                        story.setImgurl(obj.getString("imgurl"));
                        story.setChapter(obj.getString("chapter"));
                        story.setRatingtotal(obj
                                .getString("ratingtotal"));
                        story.setRatingcount(obj
                                .getString("ratingcount"));
                        story.setDateupdate(obj.getString("dateupdate"));

                        storyList.add(story);
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                adapter.notifyDataSetChanged();
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError volleyError) {
                VolleyLog.d(TAG, "Error: " + volleyError.getMessage());
                volleyError.printStackTrace();
                Toast.makeText(getBaseContext(), "Có lỗi xảy ra trong quá trình tải truyện \n" + volleyError.getMessage(), Toast.LENGTH_LONG).show();
                hidePDialog();
            }
        });
        AppController.getInstance().addToRequestQueue(storyReq);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        hidePDialog();
    }

    private void hidePDialog() {
        if (pDialog != null) {
            pDialog.dismiss();
            pDialog = null;
        }
    }


    /**
     * Kiem tra ket noi cua dien thoai
     *
     * @return
     */
    public boolean isOnline() {
        ConnectivityManager conMgr = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo i = conMgr.getActiveNetworkInfo();
        if (i == null)
            return false;
        if (!i.isConnected())
            return false;
        if (!i.isAvailable())
            return false;
        return true;
    }
}
